import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import model.UserInfo;

public class PostDataMgr
{
    private static PostDataMgr instance = new PostDataMgr();
    
    private Invocable inv;
    
    private PostDataMgr()
    {
        try
        {
            ScriptEngineManager sem = new ScriptEngineManager();
            ScriptEngine se = sem.getEngineByName("js");
            se.eval(new InputStreamReader(getClass().getResourceAsStream("js/crypto-md5-hmac.js")));
            se.eval(new InputStreamReader(getClass().getResourceAsStream("js/aes-enc.js")));
            se.eval(new InputStreamReader(getClass().getResourceAsStream("js/base64.js")));
            se.eval(new InputStreamReader(getClass().getResourceAsStream("js/mouse.js")));
            se.eval(new InputStreamReader(getClass().getResourceAsStream("js/PGencode.js")));
            se.eval(new InputStreamReader(getClass().getResourceAsStream("js/rsa.js")));
            inv = (Invocable) se;
        }
        catch (Exception e)
        {
            System.out.println(e);
        }
    }
    
    public static PostDataMgr getInstance()
    {
        return instance;
    }
    
    public List<Map<String, String>> getPostData(List<UserInfo> itemList)
    {
        List<Map<String, String>> postDataList = new ArrayList<Map<String, String>>();
        for (int i = 0; i < itemList.size(); i++)
        {
            postDataList.add(getPostData(itemList.get(i)));
        }
        return postDataList;
    }

    public Map<String, String> getPostData(UserInfo item)
    {
        try
        {
            String key = (String) inv.invokeFunction("md5", item.getGovernmentId(), item.getProductName());
            String payload = (String) inv.invokeFunction("getPayload", item.toString());
            
            Map<String, String> postData = new HashMap<String, String>();
            postData.put("key", key);
            postData.put("payload", payload);
            postData.put("governmentId", item.getGovernmentId());
            postData.put("rowIndex", String.valueOf(item.getRowIndex()));
            return postData;
        }
        catch (Exception e)
        {
            System.out.println(e);
        }
        return null;
    }
}
